package cn.moningxi.controller;

import cn.moningxi.bean.GoodsBusiness;
import cn.moningxi.service.GoodsBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class GoodsBusinessController {

    @Autowired
    private GoodsBusinessService goodsBusinessService;

    /**
     * 查询所有店铺信息
     *
     * @param modelAndView
     * @return
     */
    @RequestMapping("/allBusiness")
    public ModelAndView queryAllBusiness(ModelAndView modelAndView) {
        List<GoodsBusiness> business = goodsBusinessService.queryAllBusiness();
        modelAndView.addObject("business", business);
        modelAndView.setViewName("backstage/business-list");
        return modelAndView;
    }

    /**
     * 跳转到编辑店铺信息界面
     *
     * @param modelAndView
     * @param BID
     * @return
     */
    @RequestMapping("/editBusnessInfo/{BID}")
    public ModelAndView editBusinessInfo(ModelAndView modelAndView, @PathVariable("BID") String BID) {
        System.out.println("店铺编号：" + BID);
        GoodsBusiness goodsBusiness = goodsBusinessService.selectByBusinessID(BID);
        System.out.println("店铺修改之前的信息：" + goodsBusiness);
        modelAndView.addObject("goodsBusiness", goodsBusiness);
        modelAndView.setViewName("backstage/business-edit");
        return modelAndView;
    }

    /**
     * 将修改后的店铺信息更新到数据库中
     *
     * @param model
     * @param goodsBusiness
     * @return
     */
    @RequestMapping(value = "/updateBusniessInfo", method = RequestMethod.POST)
    public String updateBusniessInfo(Model model, GoodsBusiness goodsBusiness) {
        System.out.println("店铺修改之后的信息：" + goodsBusiness);
        goodsBusinessService.updateBusniessInfo(goodsBusiness);
        return "redirect:/allBusiness";
    }

    @RequestMapping(value = "/addBusniess", method = RequestMethod.POST)
    public ModelAndView addBusniess(ModelAndView modelAndView, GoodsBusiness goodsBusiness) {
        System.out.println("新增店铺信息：" + goodsBusiness);
        GoodsBusiness bySn = goodsBusinessService.queryBySn(goodsBusiness.getBusinessSn());
        if (bySn != null) {
            modelAndView.addObject("mesage", "店铺代码已存在");
            modelAndView.addObject("goodsBusiness", goodsBusiness);
            modelAndView.setViewName("backstage/business-add");
        } else {
            goodsBusinessService.addBusniess(goodsBusiness);
            modelAndView.setViewName("redirect:/allBusiness");
        }
        return modelAndView;
    }
}
